package whu.cn.whushare.ui.main.known;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

//主要用于设置历史记录的保存时间？？
public class SearchHistorySPManager {
    private static SearchHistorySPManager instance;
    private static final String SEARCH_HISTORY_FIRST_SP = "searchHistoryFirstSP";
    private static final String SEARCH_HISTORY_SECOND_SP = "searchHistorySecondSP";
    private Context mContext;

    private int max_size = 64;
    private SharedPreferences sp1;
    private SharedPreferences sp2;

    private SearchHistorySPManager(Context context) {
        mContext = context.getApplicationContext();
        sp1 = mContext.getSharedPreferences(SEARCH_HISTORY_FIRST_SP, Context.MODE_PRIVATE);
        sp2 = mContext.getSharedPreferences(SEARCH_HISTORY_SECOND_SP, Context.MODE_PRIVATE);
    }

    //获取SearchHistorySPManager的唯一实例对象
    public static SearchHistorySPManager getInstance(Context context) {
        if (instance == null) {
            synchronized (SearchHistorySPManager.class) {
                if (instance == null)
                    instance = new SearchHistorySPManager(context);
            }
        }
        return instance;
    }

    //返回sp1和sp2中所有键值经过排序后的列表
    public List<String> getAll() {
        final Map<String, Long> map = (Map<String, Long>) sp1.getAll();
        map.putAll((Map<String, Long>) sp2.getAll());       //map中包含sp1和sp2中所有preference的key/value集合
        List<String> keys = new ArrayList<>(map.keySet());
        Collections.sort(keys, new Comparator<String>() {
            @Override
            public int compare(String lhs, String rhs) {
                return (map.get(lhs) > map.get(rhs)) ? 1 : -1;
            }
        });
        return keys;
    }

    //判断字符串str是否存在，如果sp1或者sp2中包含字符串str，返回true；否则返回false
    public boolean isExists(String str) {
        return isExistsKey(getKey(str)) != -1;
    }

    public int isExistsKey(String key) {
        if (sp1.contains(key))
            return 1;
        else if (sp2.contains(key))
            return 2;
        return -1;
    }

    public long get(String str) {
        String key = getKey(str);
        return getSP(key);
    }

    private long getSP(String key) {
        int position = isExistsKey(key);        //position表示字符串key所在的位置，1表示在sp1中，2表示在sp2中，-1表示不存在
        switch (position) {
            case 1:
                return sp1.getLong(key, 0L);    //从key这个preference中检索一个long值，不存在则返回0L
            case 2:
                return sp2.getLong(key, 0L);
            default:
                return 0L;
        }
    }

    /**
     * 保存字符串str为一个long类型的值，value为系统当前时间
     * @param str - 待修改的字符串str
     */
    public void save(String str) {
        saveSP(getKey(str), System.currentTimeMillis());
    }

    /**
     * 保存sharedPreference
     * 若key在sp1或sp2中，则修改key的值为time所对应的值
     * 若key不存在，则添加key到恰当的sharedPreference中
     * @param key - 待修改的字符串
     * @param time - 需要保存的值
     */
    private void saveSP(String key, long time) {
        int position = isExistsKey(key);
        switch (position) {
            case 1:
                sp1.edit().putLong(key, time).commit();
                break;
            case 2:
                sp2.edit().putLong(key, time).commit();
                break;
            default:
                addSP(key, time);
                break;
        }
    }

    private void addSP(String key, long time) {
        if (size(sp1) < max_size) {
            sp1.edit().putLong(key, time).commit();
            return;
        }

        if (size(sp2) < max_size) {
            sp2.edit().putLong(key, time).commit();
            if (size(sp2) == max_size)
                sp1.edit().clear().commit();
        } else {
            sp2.edit().clear().putLong(key, time).commit();
        }
    }

    private int size(SharedPreferences sp) {
        return sp.getAll().size();
    }

    private String getKey(String key) {
        return key;
    }
}
